package com.dna.utils;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;
import org.springframework.cglib.beans.BeanMap;

/**
 * 关于Map的工具类.
 * 
 * @author 方涛升
 * 
 * @version 2018-03-27
 */
public class MapUtils {

	/**
	 * Map转换层Bean，使用泛型免去了类型转换的麻烦。
	 */
	public static <T> T map2Bean(Map<String, Object> map, Class<T> clazz) {
		T bean = null;
		try {
			bean = clazz.newInstance();
			BeanUtils.populate(bean, map);
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
		return bean;
	}
	
	
	 //Map转换为JavaBean  
	    public static <T> T mapTbean(Map<String,Object> map,Class<T> clz) throws Exception{  
	        //创建JavaBean对象  
	        T obj = clz.newInstance();  
	        //获取指定类的BeanInfo对象  
	        BeanInfo beanInfo = Introspector.getBeanInfo(clz, Object.class);  
	        //获取所有的属性描述器  
	        PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();  
	        for(PropertyDescriptor pd:pds){  
	            Object value = map.get(pd.getName());  
	            Method setter = pd.getWriteMethod();  
	            setter.invoke(obj, value);  
	        }  
	          
	        return  obj;  
	    }
	    
	    /** 
	     * 将map装换为javabean对象 
	     * @param map 
	     * @param bean 
	     * @return 
	     */  
	    public static <T> T mapToBean(Map<String, String> map,T bean) {  
	        BeanMap beanMap = BeanMap.create(bean);  
	        beanMap.putAll(map);  
	        return bean;  
	    } 
}